<?php
namespace App\Http\Controllers\Api\V4;

use App\Common\ApiData;
use App\Http\Controllers\Controller;
use App\Models\V2\BookSentenceModel;
use App\Models\V2\MemberModel;
use Illuminate\Http\Request;

/**
 * 书籍摘抄控制器
 *
 * */
class BookSentenceController extends Controller{

    private $apiData;
    public function __construct()
    {
        $this->apiData = new ApiData();
    }

    /**
     * 获得书籍摘抄句子
     * */
    public function get_sentences(Request $request)
    {
        $bookSentenceModel  = new BookSentenceModel();
        $sentences          = $bookSentenceModel->get_book_sentences();
        $mobile             = $request->input('mobile',"");
        $key                = $request->input('key',"");
        $userId             = 0;

        if($mobile && $key)
        {
            $memberModel        = new MemberModel();
            $memberInfo         = $memberModel->get_member_info_by_mobile_key($mobile,$key);
            if(!$memberInfo)
            {
                return apiData()->send(4001,'账号不存在');
            }
            $userId             = $memberInfo->UserID;
        }

        foreach($sentences as $sentence)
        {
            $time = strtotime($sentence->publish_date);
            $sentence->publish_date    = date('Y/m/d',$time);
            $sentence->bg_img          = env('HOST')."/".$sentence->bg_img;
            $users                     = explode(',',trim($sentence->like_users,','));
            $sentence->like_times      = count($users);
            $sentence->is_like         = ($userId > 0 && in_array($userId,$users)) ? 1 : 0;
        }

        return $this->apiData->set_data('data',$sentences)
            ->send_old(200,'ok');
    }


    /**
     * 获取句子详细信息
     * */
    public function get_sentence_detail(Request $request)
    {
        $mobile     = $request->input('mobile');
        $key        = $request->input('key');
        $sentenceId = $request->input('sentenceId',0);
        $booksentenceModel  = new BookSentenceModel();

        if($mobile && $key)
        {
            $memberModel    = new MemberModel();
            $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
            $userId         = $memberInfo->UserID;
            $userName       = $memberInfo->YourName;
        }
        else
        {
            $userId         = 0;
            $userName       = "";
        }

        if($sentenceId == 0)
        {
            return apiData()->send(3001,'不存在该图片');
        }
        $booksentenceInfo           = $booksentenceModel->get_book_sentence_detail($sentenceId,$userId);
        $users                      = explode(',',$booksentenceInfo->like_users);
        $booksentenceInfo->like_times= count($users);

        $shareImg   = $this->get_sentence_img($booksentenceInfo,$userId,$userName);

        $booksentenceInfo->bg_img   = env('HOST')."/".$booksentenceInfo->bg_img;
        $booksentenceInfo->share_img = env('HOST')."/".$shareImg;//env('HOST')."/uploads/guozheng/images/common/sentence.png";

        return $this->apiData->set_data('data',$booksentenceInfo)->send_old(200,'ok');
    }


    /**
     * 合成分享的图片
     * */
    public function get_sentence_img($booksentenceInfo,$userId,$userName)
    {
        $bgImg  = $booksentenceInfo->bg_img;
        $text   = $booksentenceInfo->content;

        begin:
        $fileName   = md5($text.$bgImg)."-".$userId.".jpg";
        $file       = "uploads/guozheng/images/sentence/".$fileName;

        if(file_exists($file))
        {
            return $file;
        }

        //只有学习官才会有对应的二维码,普通会员是没有的
        if($userId > 0)
        {
            //检查用户二维码是否存在
            $qrImg  = "uploads/guozheng/images/qrcode/{$userId}.png";
            $text   = "http://wx.laohoulundao.com/web/weblogin/getWebLogin?userId=".$userId;

            //创建二维码
            if(!file_exists($qrImg))
            {
                mk_dir(dirname($qrImg));
                create_qrcode($qrImg,$text);
            }
        }
        else
        {
            $qrImg  = "images/downerweima.png";
        }

        //这里主要是合成图片

        list($maxw,$maxh,$imgType)    = getimagesize($bgImg);

        switch($imgType)
        {
            case 1:$bg = imagecreatefromgif($bgImg); break;
            case 2:$bg = imagecreatefromjpeg($bgImg); break;
            case 3:$bg = imagecreatefrompng($bgImg);  break;
        }

        list($maxw, $maxh) = getimagesize($bgImg);

        $x = 25;
        $w = (int) $maxw*0.21;
        $h = $w;
        $y = 1665;

        //合成二维码
        $qr             = imagecreatefrompng($qrImg);
        list($qw,$qh)   = getimagesize($qrImg);
        imagecopyresized($bg,$qr,$x,$y,25,25,$w,$h,$qw-50,$qh-50);

        //写文字
        if($userId > 0)
        {
            $grayColor      = imagecolorallocate($bg,100,100,100);
            $fontFile       = public_path('images/didi/zhunjian.ttf');
            $yellowColor    = imagecolorallocate($bg,241,145,73);
            $baseLeft       = 625;
            $singleLen      = 41;
            $nameLen        = mb_strlen($userName) * $singleLen;

            //写字
            imagettftext($bg,25,0,$baseLeft - $nameLen - 2 * $singleLen + 7,$maxh - 110,$grayColor,$fontFile,"我是");
            imagettftext($bg,25,0,620,$maxh - 110,$grayColor,$fontFile,"邀请你一起加入教导读书会");
            imagettftext($bg,30,0,$baseLeft - $nameLen -5,$maxh - 109,$yellowColor,$fontFile,$userName);
        }

        //创建缩略图
        //$neww   = $maxw/1.5;
        //$newh   = $maxh/1.5;
        //$thumb  = imagecreatetruecolor($neww, $newh); ////创建底图
        //imagecopyresized($thumb,$bg,0,0,0,0,$neww,$newh,$maxw,$maxh); //复制背景图片
        //imagejpeg($thumb,$file);    //生成图片

        imagejpeg($bg,$file);


        //imagedestroy($thumb);
        imagedestroy($bg);
        return $file;
    }

    /**
     * 添加或取消对句子的点赞
     * */
    public function add_or_cancel_like_sentence(Request $request)
    {
        $sentenceId = $request->input('sentenceId');
        $key        = $request->input('key');
        $mobile     = $request->input('mobile');

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        $userId         = $memberInfo->UserID;
        $sentenceModel  = new BookSentenceModel();
        $sentenceInfo   = $sentenceModel->get_book_sentence_detail($sentenceId,$userId);
        $users          = $sentenceInfo->like_users;
        $users          = explode(',',$users);
        if($sentenceInfo->is_like == 1) //已点赞,取消
        {
            array_unset_value($users,$userId);
        }
        else    //未点赞，添加
        {
            array_push($users,$userId);
        }
        $users  = implode(',',$users);
        $sentenceModel->update_sentence($sentenceId,['like_users'=>$users]);
        return $this->apiData->send(200,'ok');
    }
}
